import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { Button, message, Col, Row, Form, Select, Spin, Input, Radio, Icon, AutoComplete } from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
import menuRoute from 'routes/menuRoute'
import AddressPicker from 'containers/financial-management/wait-for-billing/new-billing/address-picker'
import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import Chooser from 'components/chooser'
import 'styles/setting/wait-for-billing/edit-rule.scss'

import waitForBillingService from "../wait-for-billing.service";

class EditBillingRule extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showAdressPicker: false,
      radioValue: 'ALL',
      startMonth: '',
      startDay: '',
      endMonth: '',
      endDay: '',
      loading: '',
      invoiceTitle: [],
      accountList: [],
      personDepartment: [],
      billingType: JSON.stringify(props.billingType) !== "{}" ? props.billingType : props.params.billingType,
      dayOptions: [],
      sectionMatch: {
        companyName: "-"
      },
      ruleData: {
        "invoiceTypeResp": {}
      },
      defaultAddressInfo: {},
      didiCompanyOptions: [],
      ruleTypeOptions: [{ name: messages('financial-management.key452'/*增值税专用发票*/), type: 'ORDINARY' }, { name: messages('financial-management.key453'/*增值税普通发票*/), type: 'SPECIAL' }],
      commercialTypeOptions: [{ label: messages('financial-management.key454'/*不含商务卡*/), key: 'NOT_INCLUDE' }, { label: messages('financial-management.key432'/*全部*/), key: 'ALL' }],
      paymentTypeOptions: [{ label: messages('financial-management.key432'/*全部*/), key: null }, { label: messages('financial-management.key411'/*个人垫付*/), key: 1001 }, { label: messages('financial-management.key412'/*公司垫付*/), key: 1002 }],
      dataSource: [],
      taxpayerNumber: ''
    };
  }

  componentWillMount() {
    const { billingType } = this.state;
    let paymentTypeOptions = this.state.paymentTypeOptions;
    if (billingType === 'DIDI') {
      paymentTypeOptions = [{ label: messages('financial-management.key411'/*个人垫付*/), key: 1001 }];
    }
    this.setState({ loading: true, paymentTypeOptions });
    BillingService.getSmartRuleDetail(this.props.params.id).then(res => {
      let ruleData = res.data;
      this.getCompanyAccountList()
      this.getReceipPeriod(ruleData)
      this.getDayOptions()
      this.getReceiptDetail(ruleData);
      this.getVendorInvoiceType()
      // this.getBillContactDetail(ruleData)
      this.setState({ ruleData: ruleData, loading: false })
    })
  }
  //获取供应商发票类型
  getVendorInvoiceType = (isDefault = false) => {
    const { billingType, taxpayerNumber } = this.state;
    BillingService.getVendorInvoiceType(billingType, taxpayerNumber).then(res => {
      if (res.data && res.data.length > 0) {
        this.setState({ ruleTypeOptions: res.data }, () => {
          isDefault && this.props.form.setFieldsValue({ invoiceApplyType: res.data[0].type });
        });
      }
    }).catch(e => {
      this.setState({ ruleTypeOptions: [] }, () => {
        this.props.form.setFieldsValue({ invoiceApplyType: undefined });
      });
      message.error(e.response.data.message);
    })
  }

  //根据发票类型状态切换收件信息
  switchReceiving = (type) => {
    let email = ['ELECTRONICORDINARY'];
    if (type && ~email.indexOf(type)) {
      return true;
    }
    return false;
  }

  componentDidMount() {
    let commercialTypeOption = this.state.commercialTypeOptions;
    waitForBillingService.getCommercialType(this.props.company.companyOID).then(res => {
      if (res.data.rows && res.data.rows.length > 0) {
        res.data.rows.map(item => {
          let values = {};
          values.label = item.description;
          values.key = item.cardTypeCode;
          commercialTypeOption.push(values);
        })
      }
      this.setState({ commercialTypeOptions: commercialTypeOption });
    });
  }

  getReceipPeriod(value) {
    switch (value.receiptedPeriodState) {
      case 'ALL': {
        this.setState({ radioValue: 'ALL' })
        break;
      }
      case 'CURRENTMONTH': {
        this.setState({ radioValue: 'CURRENTMONTH' })
        break;
      }
      case 'CUSTOM': {
        this.setState({ radioValue: 'CUSTOM', startMonth: value.startMonth.toString(), startDay: value.startDay.toString(), endMonth: value.endMonth.toString(), endDay: value.endDay.toString() })
        break;
      }
    }
  }

  onRadioChange = (e) => {
    this.setState({ radioValue: e.target.value })
  };

  getReceiptDetail = (value) => {


    //按单据信息 法人实体
    if (value.expenseSearchEntityOIDs && value.expenseSearchEntityOIDs.length > 0) {
      BillingService.getBatchCorporationEntityList(value.expenseSearchEntityOIDs).then(res => {
        value.selectedExpenseSearchEntity = res.data;
      })
    } else {
      value.selectedExpenseSearchEntity = [];
    }

    //按单据信息 部门
    if (value.expenseSearchDepartmentOIDs && value.expenseSearchDepartmentOIDs.length > 0) {
      BillingService.getBatchDepartmentList(value.expenseSearchDepartmentOIDs).then(res => {
        res.data.map(item => {
          item.departmentOid = item.departmentOID
        })
        value.selectedExpenseDepartment = res.data;
      })
    } else {
      value.selectedExpenseDepartment = [];
    }

    //按单据信息 成本中心
    if (value.costCenterItemOIDs && value.costCenterItemOIDs.length > 0) {
      BillingService.getBatchCostCenterList(value.costCenterItemOIDs).then(res => {
        value.selectedCostCenter = res.data;
      })
    } else {
      value.selectedCostCenter = [];
    }

    //查询地址信息详情
    value.billingContactOID && BillingService.getBillContactDetail(value.billingContactOID).then(res => {
      this.setState({
        defaultAddressInfo: res.data
      })
    })
  }

  getDayOptions = () => {
    const { dayOptions } = this.state;
    for (let i = 1; i < 32; i++) {
      dayOptions.push(i)
    }
    this.setState({ dayOptions })
  }

  //获取公司 滴滴账户
  getCompanyAccountList = () => {
    BillingService.getCompanyAccount(this.state.billingType, this.props.company.companyOID).then(res => {
      this.setState({ accountList: res.data }, () => {
        this.getInvoiceTitle();
      })
    })
  }

  //获得抬头信息
  getInvoiceTitle = () => {
    let params = {
      companyOid: this.props.company.companyOID
    }
    BillingService.getInvoiceTitle(this.state.billingType, params).then(res => {
      if (res.data) {
        this.setState({ invoiceTitle: res.data })
      }
    })
  }

  handleCancel = () => {
    this.context.router.push(menuRoute.getRouteItem('wait-for-billing-list').url.replace(':billingType', this.state.billingType))
  };

  showAdressPicker = () => {
    this.setState({ showAdressPicker: true });
  };

  //自定义周期
  startMonthChange = (value) => {
    let { ruleData } = this.state;
    ruleData.startMonth = value
    this.setState({ ruleData })
  };

  startDayChange = (value) => {
    let { ruleData } = this.state;
    ruleData.startDay = value
    this.setState({ ruleData })
  }

  endMonthChange = (value) => {
    let { ruleData } = this.state;
    ruleData.endMonth = value
    this.setState({ ruleData })
  }

  endDayChange = (value) => {
    let { ruleData } = this.state;
    ruleData.endDay = value
    this.setState({ ruleData })
  }

  //确认选择完地址
  handleChooseAddress = (value) => {
    let { defaultAddressInfo, ruleData } = this.state;
    defaultAddressInfo.billingContactOID = value.billingContactOID;
    defaultAddressInfo.country = value.country;
    defaultAddressInfo.stateProvince = value.stateProvince;
    defaultAddressInfo.cityRegion = value.cityRegion;
    defaultAddressInfo.area = value.area;
    defaultAddressInfo.streetLine = value.streetLine;
    defaultAddressInfo.phone = value.phone;
    defaultAddressInfo.zipCode = value.zipCode;
    defaultAddressInfo.fullName = value.fullName;
    defaultAddressInfo.isDefault = value.isDefault;
    ruleData.billingContactOID = value.billingContactOID;
    delete defaultAddressInfo.explicitAddress
    this.setState({ defaultAddressInfo, ruleData })
  }

  AddressPickerCancel = () => {
    this.setState({ showAdressPicker: false });
  };

  validateData = (ruleData) => {

    return new Promise((resolve, reject) => {
      if (this.state.radioValue !== 'CUSTOM') {
        return resolve(true)
      } else {
        if (!ruleData.startMonth) {
          message.error(messages('financial-management.key455'/*开始月份必选*/))
          return reject(false)
        }
        if (!ruleData.endMonth) {
          message.error(messages('financial-management.key456'/*结束月份必选*/))
          return reject(false)
        }
        if (!ruleData.startDay) {
          message.error(messages('financial-management.key457'/*开始日期必选*/))
          return reject(false)
        }
        if (!ruleData.endDay) {
          message.error(messages('financial-management.key458'/*结束日期必选*/))
          return reject(false)
        }
        if (ruleData.startMonth === '101') {
          if (ruleData.endMonth === '101') {
            if (ruleData.startDay >= ruleData.endDay) {
              message.error(messages('financial-management.key459'/*结束时间小于开始时间*/))
              return reject(false)
            }
          }
        }
        if (ruleData.startMonth === '102') {
          if (ruleData.endMonth === '101') {
            message.error(messages('financial-management.key459'/*结束时间小于开始时间*/))
            return reject(false)
          } else {
            if (ruleData.startDay >= ruleData.endDay) {
              message.error(messages('financial-management.key459'/*结束时间小于开始时间*/))
              return reject(false)
            }
          }
        }
        return resolve(true)
      }
    })
  }

  saveReceiptConditions = (e) => {
    e.preventDefault();
    const { defaultAddressInfo, ruleData, invoiceTitle, radioValue, accountList, billingType } = this.state;

    let searchParams = {}
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.validateData(ruleData).then(() => {
          if (radioValue !== 'CUSTOM') {
            ruleData.startMonth = null;
            ruleData.startDay = null;
            ruleData.endMonth = null;
            ruleData.endDay = null;
          }
          delete values.developCircleCustom
          searchParams.startMonth = ruleData.startMonth;
          searchParams.startDay = ruleData.startDay;
          searchParams.endMonth = ruleData.endMonth;
          searchParams.endDay = ruleData.endDay;
          if (!this.switchReceiving(values.invoiceApplyType) && (!defaultAddressInfo || !defaultAddressInfo.billingContactOID)) {
            message.warn(messages('financial-management.key460'/*请选择收货地址*/));
            return;
          }
          if (!this.switchReceiving(values.invoiceApplyType)) {
            searchParams.addressDetail = defaultAddressInfo;
            searchParams.billingContactOID = defaultAddressInfo.billingContactOID;
          }
          searchParams.tenantId = this.props.tenant.id;
          if (billingType != 'CLOUD_HELIOS_HOTEL') {
            let accountInfo = accountList.filter(item => item.vendorAccountId === values.vendorAccountId)[0];
            searchParams.vendorAccountName = accountInfo ? accountInfo.vendorAccountName : null;
            searchParams.vendorAccountId = accountInfo ? accountInfo.vendorAccountId : null;
          }
          searchParams.taxpayerNumber = invoiceTitle.filter(item => item.invoice_title === values.title)[0].tax_registration_number
          searchParams.qualificationId = invoiceTitle.filter(item => item.invoice_title === values.title)[0].id
          searchParams.expenseSearchEntityOIDs = values.expenseSearchEntityOIDs === undefined ? [] : values.expenseSearchEntityOIDs.map(item => { return item.companyReceiptedOID });
          searchParams.expenseSearchDepartmentOIDs = values.expenseSearchDepartmentOIDs === undefined ? [] : values.expenseSearchDepartmentOIDs.map(item => { return item.departmentOid });
          searchParams.costCenterItemOIDs = values.costCenterItemOIDs === undefined ? [] : values.costCenterItemOIDs.map(item => { return item.costCenterItemOID });
          searchParams.receiptedPeriodState = radioValue;
          searchParams.keyInvoiceOID = this.props.params.id;
          searchParams.delete = false;
          let params = { ...values, ...searchParams }
          params.vendor = billingType;
          BillingService.updateSmartRule(params).then(res => {
            if (res.status === 200) {
              message.success(messages('financial-management.key382'/*修改成功*/))
              this.handleCancel()
            }
          }).catch(e => {
            message.success(messages('financial-management.key461'/*修改失败*/))
          })
        })
      }
    })
  }
  emailHandleChange = (value) => {
    this.setState({
      dataSource: !value || value.indexOf('@') >= 0 ? [] : [
        `${value}@${this.props.user.email && ~this.props.user.email.indexOf('@') ? this.props.user.email.split('@')[1] : ''}`,
        `${value}@163.com`,
        `${value}@126.com`,
        `${value}@qq.com`,
        `${value}@sina.com`,
      ],
    });
  };

  renderBillingType = () => {
    const { billingType } = this.state;
    let result = '';
    switch (billingType) {
      case 'DIDI':
        result = messages('financial-management.key423'/*滴滴账户*/);
        break;
      case 'CLOUD_HELIOS_HOTEL':
        result = messages('financial-management.key548'/*甄选账号*/);
        break;
      case 'SHEN_ZHOU':
        result = messages('financial-management.key549'/*神州账户*/);
        break;
      default:
        result = '';
        break;
    }
    return result;
  };

  handleChangeInvoice = value => {
    const { invoiceTitle } = this.state;
    let temp = invoiceTitle.find(item => item.invoice_title === value) || {};
    this.setState({ taxpayerNumber: temp.tax_registration_number }, () => {
      this.getVendorInvoiceType(true);
    });
  };

  render() {

    const { accountList, paymentTypeOptions, ruleData, radioValue, dayOptions, startMonth, endMonth, startDay, endDay, invoiceTitle, ruleTypeOptions, defaultAddressInfo, showAdressPicker, personDepartment, loading, commercialTypeOptions, billingType, dataSource } = this.state;
    const { getFieldDecorator } = this.props.form;
    let dateOptions = [{ label: messages('financial-management.key564')/*审核日期*/, key: 'AUDIT_PASS_DATE' }];
    let invoiceApplyType = this.props.form.getFieldValue('invoiceApplyType');
    return (
      <div style={{ width: '100%' }} className='edit-rule'>
        <Spin spinning={loading}>
          <Form>
            <Row gutter={16} type="flex" align="top">
              <Col span={8}>
                <FormItem label={messages('financial-management.key481'/*基准日期*/)}>
                  {getFieldDecorator("recDateTypeEnum", {
                    rules: [
                      {
                        required: true,
                      }
                    ],
                    initialValue: ruleData.recDateTypeEnum
                  })(
                    <Select>
                      {dateOptions.map(option => <Option key={option.key}>{option.label}</Option>)}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={16}>
                <Row>
                  <Col span={8}>
                    <FormItem label={messages('financial-management.key429'/*日期范围*/)}>
                      {getFieldDecorator('receiptedPeriodState')(
                        <div>
                          <RadioGroup value={radioValue} onChange={this.onRadioChange}>
                            <Radio value='ALL'>{messages('financial-management.key432'/*全部*/)}</Radio>
                            <Radio value='CURRENTMONTH'>{messages('financial-management.key464'/*当月*/)}</Radio>
                            <Radio value='CUSTOM'>{messages('financial-management.key465'/*自定义*/)}</Radio>
                          </RadioGroup>
                        </div>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={16}>
                    {radioValue === 'CUSTOM' && (
                      <FormItem label="">
                        {getFieldDecorator('developCircleCustom')(
                          <div>
                            <div style={{ margin: "32px 0 0 -20px" }}>
                              <Select style={{ width: 80, marginRight: 10 }} defaultValue={startMonth} onChange={this.startMonthChange}>
                                <Option value='101'>{messages('financial-management.key466'/*上月*/)}</Option>
                                <Option value='102'>{messages('financial-management.key464'/*当月*/)}</Option>
                              </Select>
                              <Select style={{ width: 60, marginRight: 10 }} defaultValue={startDay} onChange={this.startDayChange}>
                                {dayOptions.map(item => <Option key={item} value={item}>{item}</Option>)}
                              </Select>
                              <span>{messages('financial-management.key430'/*至*/)}</span>
                              <Select style={{ width: 80, marginRight: 10, marginLeft: 10 }} defaultValue={endMonth} onChange={this.endMonthChange}>
                                <Option value='101'>{messages('financial-management.key466'/*上月*/)}</Option>
                                <Option value='102'>{messages('financial-management.key464'/*当月*/)}</Option>
                              </Select>
                              <Select style={{ width: 60, marginRight: 10 }} defaultValue={endDay} onChange={this.endDayChange}>
                                {dayOptions.map(item => <Option key={item} value={item}>{item}</Option>)}
                              </Select>
                            </div>
                          </div>
                        )}
                      </FormItem>
                    )}
                  </Col>
                </Row>
              </Col>
              <Col span={8}>
                <FormItem label={messages('financial-management.key462'/*规则名称*/)}>
                  {getFieldDecorator("keyInvoiceName", {
                    rules: [
                      {
                        required: true,
                        message: messages('financial-management.key463'/*请填写规则名称*/)
                      }
                    ],
                    initialValue: ruleData.keyInvoiceName
                  })(
                    <Input placeholder={messages('financial-management.key463'/*请填写规则名称*/)} />
                  )}
                </FormItem>
              </Col>
              {billingType != 'CLOUD_HELIOS_HOTEL' && <Col span={8}>
                <FormItem label={this.renderBillingType()}>
                  {getFieldDecorator('vendorAccountId', {
                    rules: [{
                      required: true
                    }],
                    initialValue: ruleData.vendorAccountId
                  })(
                    <Select>
                      {accountList.map(option => <Option key={option.vendorAccountId} >{option.vendorAccountName}</Option>)}
                    </Select>
                  )}
                </FormItem>
              </Col>}
              <Col span={8}>
                <FormItem label={messages('financial-management.key467'/*支付方式*/)}>
                  {getFieldDecorator('paymentType', {
                    initialValue: ruleData.paymentType
                  })(
                    <Select>
                      {paymentTypeOptions.map(option => <Option value={option.key} key={option.key}>{option.label}</Option>)}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('financial-management.key468'/*法人实体【单据信息】*/)}>
                  {getFieldDecorator('expenseSearchEntityOIDs', {
                    initialValue: ruleData.selectedExpenseSearchEntity
                  })(
                    <Chooser placeholder={messages('common.please.select')}
                      type='corporation_entity_all'
                      valueKey="companyName"
                      labelKey="companyName"
                      single={false}
                    />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('financial-management.key469'/*部门【单据信息】*/)}>
                  {getFieldDecorator('expenseSearchDepartmentOIDs', {
                    initialValue: ruleData.selectedExpenseDepartment
                  })(
                    <Chooser placeholder={messages('common.please.select')}
                      type='department'
                      valueKey="departmentOid"
                      labelKey="name"
                      single={false}
                    />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('financial-management.key470'/*成本中心*/)}>
                  {getFieldDecorator('costCenterItemOIDs', {
                    initialValue: ruleData.selectedCostCenter
                  })(
                    <Chooser placeholder={messages('common.please.select')}
                      type='cost_center'
                      valueKey="id"
                      labelKey="name"
                      single={false}
                    />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('financial-management.key428'/*开票抬头*/)}>
                  {getFieldDecorator("title", {
                    rules: [{
                      required: true,
                      message: messages('financial-management.key471'/*请选择发票抬头*/)
                    }],
                    initialValue: ruleData.title
                  })(
                    <Select
                      placeholder={messages('financial-management.key472'/*请选择抬头*/)}
                      onChange={this.handleChangeInvoice}
                    >
                      {invoiceTitle.map(item => <Option key={item.invoice_title}>{item.invoice_title}</Option>)}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('financial-management.key433'/*开票类型*/)}>
                  {getFieldDecorator("invoiceApplyType", {
                    rules: [{
                      required: true,
                    }],
                    initialValue: ruleData.invoiceTypeResp.type
                  })(
                    <Select >
                      {ruleTypeOptions.map(item => <Option value={item.type} key={item.type}>{item.name}</Option>)}
                    </Select>
                  )}
                </FormItem>
              </Col>
              {ruleData.bankCardType && <Col span={8}>
                <FormItem label={messages('financial-management.key436'/*商务卡支付*/)}>
                  {getFieldDecorator("bankCardType", {
                    initialValue: ruleData.bankCardType
                  })(
                    <Select >
                      {commercialTypeOptions.map(item => <Option value={item.key} key={item.key}>{item.label}</Option>)}
                    </Select>
                  )}
                </FormItem>
              </Col>}
              {this.switchReceiving(invoiceApplyType) && <Col span={8}>
                <FormItem label={messages('financial-management.key473'/*收件邮箱*/)}>
                  {getFieldDecorator("email", {
                    initialValue: ruleData.email,
                    rules: [{
                      required: true,
                      type: 'email',
                      message: `${messages('common.please.enter')}${messages('financial-management.key474'/*正确的收件邮箱*/)}`
                    }],
                  })(
                    <AutoComplete
                      dataSource={dataSource}
                      onChange={this.emailHandleChange}
                      placeholder={messages('common.please.enter')}
                    />
                  )}
                </FormItem>
              </Col>}
            </Row>
            {!this.switchReceiving(invoiceApplyType) && (<div><div className='receive-info-title'><span style={{ color: 'red' }}>* </span>{messages('financial-management.key475'/*收件信息*/)}</div>
              <div className='receive-info-content'>
                {defaultAddressInfo.fullName}&nbsp;&nbsp;{defaultAddressInfo.phone}&nbsp;&nbsp;{defaultAddressInfo.country}{defaultAddressInfo.stateProvince}{defaultAddressInfo.cityRegion}{defaultAddressInfo.streetLine}
                {defaultAddressInfo && defaultAddressInfo.isDefault && <div className='default-button'>{messages('financial-management.key476'/*默认地址*/)}</div>}
              </div>
              <div className='more-address' onClick={this.showAdressPicker}>{messages('financial-management.key477'/*更多地址*/)}<Icon type="down-circle-o" style={{ marginLeft: "5px" }} /></div></div>)}
            <div className='footer-buttons'>
              <Button style={{ marginRight: 20 }} htmlType="submit" type="primary" onClick={this.saveReceiptConditions}>{messages('financial-management.key478'/*确定*/)}</Button>
              <Button onClick={this.handleCancel}>{messages('financial-management.key401'/*取消*/)}</Button>
            </div>
          </Form>
          {showAdressPicker && <AddressPicker visible={showAdressPicker} onCancel={this.AddressPickerCancel} moreAdress={value => this.handleChooseAddress(value)} flag={'edit'} billingContactOID={ruleData.billingContactOID} />}
        </Spin>
      </div>
    )
  }

}

EditBillingRule.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    billingType: state.billing.billingType,
    tenant: state.login.tenant
  }
}

const WrappedEditBillingRule = Form.create()(EditBillingRule);

export default connect(mapStateToProps)(WrappedEditBillingRule);
